import { reactive } from 'vue'
import { storageManager } from '@/utils/storage'

export function useVoice(){
  // 响应式语音状态
  const voice = reactive({
    listening: false,
    recognizing: false,
    recognizedText: '',
    recordPath: '',
    recordDuration: 0
  })
  
  let recorder = null
  let recordTimer = null
  
  // 初始化录音管理器
  const initRecorder = () => {
    if(recorder) return
    if(typeof wx !== 'undefined' && wx.getRecorderManager){
      recorder = wx.getRecorderManager()
      
      // 录音停止回调
      recorder.onStop((res) => {
        voice.listening = false
        voice.recognizing = true
        voice.recordPath = res.tempFilePath
        
        // 模拟语音识别（实际应调用微信同声传译/腾讯云ASR）
        setTimeout(() => {
          const mockTexts = [
            '缴电费', '查天气', '打电话给儿子', 
            '药品识别', '预约挂号', '叫车出行'
          ]
          voice.recognizedText = mockTexts[Math.floor(Math.random() * mockTexts.length)]
          voice.recognizing = false
          
          // 保存识别历史
          storageManager.addVoiceHistoryItem({
            text: voice.recognizedText,
            time: Date.now()
          })
          
          // 触觉反馈
          if(uni.vibrateShort){
            try { uni.vibrateShort({ type: 'light' }) } catch(e){}
          }
        }, 800)
      })
    }
  }
  
  // 开始录音
  const handleVoiceStart = () => {
    initRecorder()
    if(!recorder){
      uni.showToast({ title:'当前平台不支持录音', icon:'none' })
      return
    }
    
    // 触觉反馈
    if(uni.vibrateShort){
      try { uni.vibrateShort({ type: 'medium' }) } catch(e){}
    }
    
    voice.listening = true
    voice.recognizedText = ''
    recorder.start({ format: 'mp3' })
    
    // 开始计时
    voice.recordDuration = 0
    recordTimer = setInterval(() => {
      voice.recordDuration += 1
    }, 1000)
  }
  
  // 结束录音
  const handleVoiceEnd = () => {
    if(!recorder || !voice.listening) return
    
    clearInterval(recordTimer)
    recorder.stop()
    
    // 触觉反馈
    if(uni.vibrateShort){
      try { uni.vibrateShort({ type: 'light' }) } catch(e){}
    }
  }
  
  // 取消录音
  const handleVoiceCancel = () => {
    if(!recorder || !voice.listening) return
    
    clearInterval(recordTimer)
    voice.listening = false
    voice.recordDuration = 0
    uni.showToast({ title:'已取消录音', icon:'none' })
  }
  
  // 清理资源
  const cleanup = () => {
    clearInterval(recordTimer)
    if(recorder && voice.listening){
      recorder.stop()
    }
  }
  
  return { 
    voice, 
    handleVoiceStart, 
    handleVoiceEnd, 
    handleVoiceCancel,
    cleanup
  }
}

